import os
import re
from datetime import datetime
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
import requests


class DocxUtils:
    def __init__(self, template_path):
        self.template_path = template_path
        self.document = None

    def load_template(self):
        """加载模板文档"""
        try:
            self.document = Document(self.template_path)
        except Exception as e:
            print(f"加载模板失败: {e}")
            raise

    def _call_ai(self, prompt):
        """
        调用DeepSeek AI接口进行文本润色
        """
        try:
            DEEPSEEK_KEY = "sk-d34cd6ffbfe3477b98da40cc8f8f4267"
            MODEL = "deepseek-chat"
            
            headers = {
                "Authorization": f"Bearer {DEEPSEEK_KEY}",
                "Content-Type": "application/json"
            }
            
            payload = {
                "model": MODEL,
                "messages": [{"role": "user", "content": prompt}],
                "max_tokens": 4096,
                "temperature": 0.2,
            }
            
            response = requests.post(
                "https://api.deepseek.com/v1/chat/completions",
                headers=headers,
                json=payload,
                timeout=180
            )
            response.raise_for_status()
            return response.json()["choices"][0]["message"]["content"].strip()
        except Exception as e:
            print(f"调用AI润色失败: {e}")
            return None

    def _polish_text(self, text):
        """
        使用AI对文本进行润色
        """
        if not text.strip():
            return text
            
        prompt = f"""
        你是专业的新闻编辑，请对以下中文新闻内容进行润色，要求：
        1. 保持原意不变
        2. 语言更加正式规范
        3. 语句通顺流畅
        4. 只输出润色后的内容，不要添加任何说明
        
        内容如下：
        {text}
        """
        
        polished = self._call_ai(prompt)
        return polished if polished else text

    def _set_font(self, paragraph, font_name='仿宋', font_size=15, color=None, bold=False):
        """
        设置段落字体
        """
        for run in paragraph.runs:
            font = run.font
            font.name = font_name
            font._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
            font.size = Pt(font_size)
            if color:
                font.color.rgb = RGBColor(*color)
            font.bold = bold
            
    def _add_heading(self, text, level=1):
        """
        添加标题
        """
        paragraph = self.document.add_paragraph()
        run = paragraph.add_run(text)
        font = run.font
        if level == 1:  # 主标题
            font.name = '黑体'
            font._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
            font.size = Pt(22)
            font.bold = True
            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        elif level == 2:  # 栏目标题
            font.name = '黑体'
            font._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
            font.size = Pt(16)
            font.bold = True
            paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
            # 设置段落间距
            paragraph.paragraph_format.space_before = Pt(10)
            paragraph.paragraph_format.space_after = Pt(10)
        return paragraph
            
    def _add_content(self, text):
        """
        添加正文内容
        """
        paragraph = self.document.add_paragraph()
        run = paragraph.add_run(text)
        font = run.font
        font.name = '仿宋'
        font._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
        font.size = Pt(15)
        # 设置段落格式
        paragraph_format = paragraph.paragraph_format
        paragraph_format.space_before = Pt(0)
        paragraph_format.space_after = Pt(0)
        paragraph_format.line_spacing = 1.5
        return paragraph
        
    def generate_daily_report(self, news_data, output_path):
        """
        生成日报Word文档
        """
        try:
            # 加载模板
            if os.path.exists(self.template_path):
                self.document = Document(self.template_path)
                logger.info(f"加载模板文件: {self.template_path}")
            else:
                self.document = Document()
                logger.info("未找到模板文件，创建新文档")
                # 添加默认标题
                self._add_heading('班超要闻', level=1)
                
            # 更新日期
            today = datetime.date.today().strftime('%Y年%m月%d日')
            date_paragraph = self.document.add_paragraph()
            date_run = date_paragraph.add_run(f'({today})')
            date_font = date_run.font
            date_font.name = '仿宋'
            date_font._element.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
            date_font.size = Pt(15)
            date_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            date_paragraph.paragraph_format.space_after = Pt(20)
            
            # 添加各栏目内容
            sections = [
                ("国内新闻", news_data.get("国内新闻", [])),
                ("国际新闻", news_data.get("国际新闻", [])),
                ("兵团新闻", news_data.get("兵团新闻", [])),
                ("镁业新闻", news_data.get("镁业新闻", [])),
                ("国际原油", news_data.get("国际原油", []))
            ]
            
            for section_title, items in sections:
                if items:
                    # 添加栏目标题
                    self._add_heading(section_title, level=2)
                    # 添加内容条目
                    for item in items:
                        if item and not item.startswith("[") and item != "无":
                            self._add_content(item)
                            
            # 保存文档
            self.document.save(output_path)
            logger.info(f"文档已保存: {output_path}")
            return True
        except Exception as e:
            logger.error(f"生成Word文档时出错: {str(e)}")
            return False
